package recommend

import (
	"context"
	"encoding/json"
	"fmt"
	"strings"

	"mall/common/globalkey"
	"mall/common/mqueuex"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateItemLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 创建Gorse Item
func NewCreateItemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateItemLogic {
	return &CreateItemLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateItemLogic) CreateItem(req *types.CreateGorseItemReq) (*types.BaseMsgResp, error) {
	if req.Ids == nil || len(strings.TrimSpace(*req.Ids)) == 0 || req.ItemType == nil {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}
	if *req.ItemType != uint32(globalkey.AttachmentLogTypeKnowledgeBase) && *req.ItemType != uint32(globalkey.AttachmentLogTypePost) {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	m := mqueuex.DeferredCreateGorseItemMessage{
		Ids:         req.Ids,
		ContentType: pointy.GetPointer(int32(*req.ItemType)),
	}

	body, err := json.Marshal(m)
	if err != nil {
		logx.Errorf("CreateTopic createDeferredCreateGorseItemTask json.Marshal error: %+v,Please create again gorse item,entryIDs:%+v", logx.Field("detail", err.Error()), req.Ids)
		// return nil, err
	} else {
		err = l.svcCtx.KqCreateGorseItemClient.Push(string(body))
		if err != nil {
			fmt.Println("CreateTopic err", err)
			logx.Errorf("CreateTopic createDeferredCreateGorseItemTask error: %+v,Please create again gorse item,entryIDs:%+v", logx.Field("detail", err.Error()), req.Ids)
			// return nil, err
		}
	}

	return &types.BaseMsgResp{
		Msg: "添加成功",
	}, nil
}
